<template>
  <view class="page">
	 <view class="flex">
    <input class="input" type="text" v-model="inputValue" 
	placeholder="请输入一个新的分区" />
    <button class="add_btn btn" @click="addItem">添加</button>
	</view>
    <view class="list">
    	<view class="flex item" v-for="(item, index) in items" :key="index">
    	  <view class="title flex1" @click="toPage(item)">
    	  	{{ item.value }} 
    	  </view>
    	  <button class="del_btn btn" @click="removeItem(index,item.id)">移除</button>
    	</view>
    </view>
  </view>
</template>
 
<script>
export default {
  data() {
    return {
      inputValue: '',
      items: []
    };
  },
  mounted() {
  	this.load()
  },
  methods: {
	load(){ 
		var _this = this
		uni.getStorage({
		  key: 'items',
		  success: function (res) {
		    console.log('从本地读取的数据为：', res.data);
			_this.items = JSON.parse(res.data)
		  }
		});
	},
    addItem() {
	 var value = 	this.inputValue.trim()
	 if(!value) return uni.showToast({ title: '输入为空' });	
	 var values = this.items.map(e=>e.value)
     if(values.includes(value))  return uni.showToast({ title: '已存在该分区' })
	 this.items.push({
		 id:Date.now(),
		 value:value
	 });
	 this.inputValue = ''; 
	 this.save()
    },
	save(){
		uni.setStorage({
		  key: 'items',
		  data: JSON.stringify(this.items),
		  success: function () {
		    console.log('数据存储成功');
		  }
		});
	},
    removeItem(index,id) {
		var _this = this
		uni.showModal({
		    title: '提示',
		    content: '确定要移除?',
		    success: function (res) {
		        if (res.confirm) {
		            console.log('用户点击确定');
					_this.items.splice(index, 1);
					_this.save()
					_this.clearData(id)
		        } else if (res.cancel) {
		            console.log('用户点击取消');
		        }
		    }
		}); 
    },
	clearData(id){
		uni.getStorage({
			key: 'records',
			success: function(res) {
				console.log('从本地读取的数据为：', res.data);
				var all = JSON.parse(res.data)
				all = all.filter(e=>e.fid != id)
				uni.setStorage({
				  key: 'records',
				  data: JSON.stringify(all),
				  success: function () {
				    console.log('数据存储成功');
				  }
				});
			}
		});
	},
	toPage(item){
		wx.navigateTo({ url: `/pages/admin/item?id=${item.id}&value=${item.value}`})
	},
  }
};
</script>
<style>
	.input{
		flex:1;
		border: 1px solid #ccc;
		border-radius: 5px;
		height: 28px;
		padding-left: 10px;
		margin-right: 5px;
		font-size: 12px;
	}
	.btn{
		width: 100px;
		height: 30px;
		font-size: 12px;
	}
	.list{
		height: calc(100vh - 70px);
		overflow: auto;
		padding: 10px 0;
	}
	.item{
		padding: 4px 10px;
		background-color: #f1f1f1;
		margin: 2px 0;
	}
	.del_btn{
		width: 60px;
		background-color: crimson;
		color: #fff;
	}
</style>